import json

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from book.models import BookInfo
from .serializers_2 import BookSerializer


class BooksView(View):

    def post(self, request):
        # 接收
        data = json.loads(request.body.decode())
        book = BookSerializer(data=data)

        # 验证
        book.is_valid(raise_exception=True)

        # 处理
        book.save()

        # 响应
        return JsonResponse(book.validated_data, status=200)

    def get(self, request):
        books = BookInfo.objects.all()
        books = BookSerializer(books, many=True)
        return JsonResponse(books.data, safe=False, status=200)


class BookView(View):

    def get(self, request, pk):
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': '图书没找到'}, status=404)

        book = BookSerializer(book)

        return JsonResponse(book.data, status=200)

    def delete(self, request, pk):
        BookInfo.objects.filter(id=pk).delete()
        return JsonResponse({'error': '删除成功'}, status=200)

    def put(self, request, pk):
        # 接收
        data = json.loads(request.body.decode())

        # 验证
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': '图书没找到'}, status=404)

        book = BookSerializer(book, data)
        book.is_valid(raise_exception=True)

        # 处理
        book.save()

        # 相应
        return JsonResponse(book.validated_data, status=200)


